package com.ec.auth.security.config;

import com.ec.auth.security.handle.AuthenticationEntryPointHandle;
import com.ec.auth.security.handle.LogoutSuccessHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig {

    @Autowired
    private SecurityAdminConfig securityAdminConfig;

    @Autowired
    private AuthenticationEntryPointHandle authenticationEntryPoint;

    @Autowired
    private LogoutSuccessHandle logoutSuccessHandle;

//    @Autowired
//    private CorsFilter corsFilter;

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        // 禁用 csrf，前后端分离模式不需要，因为是无状态的
        httpSecurity.csrf(AbstractHttpConfigurer::disable)
                // 禁用 Session存储 -- SessionCreationPolicy.STATELESS 表示永远不会创建会话
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                // 配置允许请求
                .authorizeRequests(expressionInterceptUrlRegistry ->
                        expressionInterceptUrlRegistry.antMatchers("/login", "/captchaImage", "/register").permitAll()
                                // 下面是追加对资源的释放，并设置get请求
//                                .antMatchers(HttpMethod.GET, "/", "222.html")
                                // 其他请求需要认证
                                .anyRequest().authenticated())
                // 进制网页嵌套
                .headers().frameOptions().disable()
                .and();
        // 退出过滤器
        httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandle);
        // 创建过滤器链
        httpSecurity.apply(securityAdminConfig);
        httpSecurity.exceptionHandling(ex -> ex.authenticationEntryPoint(authenticationEntryPoint));
        return httpSecurity.build();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
